package com.zzy.utils;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;

import java.io.IOException;

/**
 * 批量操作
 */
public class BatchRequest {
    public static void main(String[] args) {
        test();
    }

    public static void test() {
        HttpHost httpHost = new HttpHost("192.168.15.128", 9200, "http");
        RestClientBuilder rb = RestClient.builder(httpHost);

        rb.setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                return builder.setConnectTimeout(20000)// 链接超时  毫秒
                        .setSocketTimeout(20000) // 请求超时  毫秒
                        ;
            }
        });

        RestHighLevelClient client = new RestHighLevelClient(rb);

        try {
            System.out.println("打开了 elasticsearch 链接。");



            BulkRequest bulkRequest =   new BulkRequest();

            bulkRequest.add(  (new IndexRequest() ).index("zzyuser").id("1005").source( XContentType.JSON , "name","李四5" )  );
            bulkRequest.add(  (new IndexRequest() ).index("zzyuser").id("1006").source( XContentType.JSON , "name","王五6" )   );
            bulkRequest.add(  (new IndexRequest() ).index("zzyuser").id("1007").source( XContentType.JSON , "name","赵六7" )   );

            BulkResponse response = client.bulk( bulkRequest , RequestOptions.DEFAULT);

            System.out.println(response.getIngestTook());
            System.out.println(response.getIngestTookInMillis());
            System.out.println(response.getTook());

            client.close();//关闭链接
            System.out.println("关闭了 elasticsearch 链接。");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}